package com.longnows.appserver.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.longnows.appserver.exception.http.ServerErrorException;
import com.longnows.appserver.model.Spec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class GenericAndJson {

    private static ObjectMapper mapper;
    @Autowired
    public void setMapper(ObjectMapper mapper){
        GenericAndJson.mapper=mapper;
    }
    public static <T> String objectToJson(T o){
        try {
            return GenericAndJson.mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }

    public static <T> T JsonToObject(String s,TypeReference<T> tr){
        try {
            if (s == null){
                return  null;
            }
            T t = GenericAndJson.mapper.readValue(s, tr);
            return t;
        } catch (JsonProcessingException e) {
            throw new ServerErrorException(9999);
        }
    }

//    public static <T> List<T> JsonToList(String s){
//        try {
//            if (s == null){
//                return  null;
//            }
//            List<T> list = GenericAndJson.mapper.readValue(s, new TypeReference<List<T>>() {
//            });
//            return list;
//        } catch (JsonProcessingException e) {
//            throw new ServerErrorException(9999);
//        }
//    }
//
//    public static <T> T JsonToList(String s, TypeReference<T> tr){
//        try {
//            if (s == null){
//                return  null;
//            }
//            T list = GenericAndJson.mapper.readValue(s, tr);
//            return list;
//        } catch (JsonProcessingException e) {
//            throw new ServerErrorException(9999);
//        }
//    }

}
